package com.alibaba.citrus.ots.platform.enhance.repository.impl;

import com.alibaba.citrus.ots.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.ots.platform.enhance.repository.OrganizationRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.model.DubboResult;
import com.alibaba.citrus.ots.platform.enhance.repository.utils.ResultUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineCreateOrganizationRequest;
import com.epoch.app.bcots.model.dto.BaselineGetChildrenOrganizationByIdCopyRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByBizIdRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByOutCodesRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByTypeRequest;
import com.epoch.app.bcots.model.dto.BaselineUpdateOrganizationRequest;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.enums.OrganizationTypeEnum;
import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhoubc
 * @description: TODO
 * @date 2021/9/3 15:01
 */
@Component
public class OrganizationRepositoryImpl implements OrganizationRepository {

    Log log = Log.getLogger(OrganizationRepositoryImpl.class);

    @Resource
    BaseDataService baseDataService;

    @Override
    @RepositoryInvoker
    public Result<String> createOrganization(OrganizationSDO sdo) {
        BaselineCreateOrganizationRequest createRequest = createRequestConverter(sdo);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineCreateOrganization(createRequest));
        if(!result.getSuccess()){
            log.error("创建组织信息失败=={}，错误原因=={}",sdo.toString(),result.getMessage());
            return Result.fail("",result.getMessage());
        }
        return Result.success((String) result.getResult());
    }

    @Override
    @RepositoryInvoker
    public Result<Boolean> editOrganization(OrganizationSDO sdo) {
        BaselineUpdateOrganizationRequest updateRequest = updateRequestConverter(sdo);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineUpdateOrganization(updateRequest));
        if(!result.getSuccess()){
            log.error("编辑组织信息失败=={}，错误原因=={}",sdo.toString(),result.getMessage());
            return Result.fail("",result.getMessage());
        }
        return Result.success(result.getSuccess());
    }

    @Override
    @RepositoryInvoker
    public OrganizationSDO getOrganizationById(String organizationId) {
        BaselineGetOrganizationByIdRequest request = new BaselineGetOrganizationByIdRequest();
        request.setId(organizationId);
        DubboResult result = ResultUtils.getDubboResult((Map) baseDataService.baselineGetOrganizationById(request));
        OrganizationSDO sdo = organizationResponseConverter((Map)result.getResult());
        return sdo;
    }

    @Override
    @RepositoryInvoker
    public List<OrganizationSDO> getAllOrganizationByBizTypeAndBizId(String bizType, String bizId) {
        BaselineGetOrganizationByBizIdRequest request = new BaselineGetOrganizationByBizIdRequest();
        request.setBizType(bizType);
        request.setBizId(bizId);
        DubboResult result = ResultUtils.getDubboResultList((Map) baseDataService.baselineGetOrganizationByBizId(request));
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    @Override
    @RepositoryInvoker
    public List<OrganizationSDO> getAllOrganization() {
        DubboResult result = ResultUtils.getDubboResultList((Map) baseDataService.baselineGetAllOrganization());
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    @Override
    @RepositoryInvoker
    public List<OrganizationSDO> getDirectChildOrganizations(String parentId, Integer status) {
        BaselineGetChildrenOrganizationByIdCopyRequest request = new BaselineGetChildrenOrganizationByIdCopyRequest();
        request.setId(parentId);
        request.setStatus(status);
        DubboResult result = ResultUtils.getDubboResultList((Map)baseDataService.baselineGetChildrenOrganizationByIdCopy(request));
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    @Override
    @RepositoryInvoker
    public List<OrganizationSDO> getOrganizationsByType(String bizType, String bizId, List<String> bizIds, String type, String parentId, List<String> parentIds) {
        BaselineGetOrganizationByTypeRequest request = new BaselineGetOrganizationByTypeRequest();
        request.setBizType(bizType);
        request.setBizId(bizId);
        request.setBizIds(bizIds);
        request.setType(type);
        request.setParentId(parentId);
        request.setParentIds(parentIds);
        DubboResult result = ResultUtils.getDubboResultList((Map) baseDataService.baselineGetOrganizationByType(request));
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    @Override
    @RepositoryInvoker
    public List<OrganizationSDO> getOrganizationByOutCodes(List<String> outCodes) {
        BaselineGetOrganizationByOutCodesRequest request = new BaselineGetOrganizationByOutCodesRequest();
        request.setOutCodes(outCodes);
        DubboResult result = ResultUtils.getDubboResultList((Map) baseDataService.baselineGetOrganizationByOutCodes(request));
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    @Override
    public List<OrganizationSDO> getOrganizationByIds(List<String> ids) {
        BaselineGetOrganizationByIdsRequest request = new BaselineGetOrganizationByIdsRequest();
        request.setIds(ids);
        DubboResult result = ResultUtils.getDubboResultList((Map) baseDataService.baselineGetOrganizationByIds(request));
        List<Map> list = (List<Map>)result.getResult();
        List<OrganizationSDO> data = list.stream().map( x -> {
            return organizationResponseConverter(x);
        }).collect(Collectors.toList());
        return data;
    }

    private BaselineCreateOrganizationRequest createRequestConverter(OrganizationSDO sdo){
        BaselineCreateOrganizationRequest baselineCreateOrganizationRequest = new BaselineCreateOrganizationRequest();
        baselineCreateOrganizationRequest.setName(sdo.getName());
        baselineCreateOrganizationRequest.setCode(sdo.getCode());
        baselineCreateOrganizationRequest.setParentId(sdo.getParentId());
        baselineCreateOrganizationRequest.setType(sdo.getType());
        baselineCreateOrganizationRequest.setBizId(sdo.getBizId());
        baselineCreateOrganizationRequest.setBizType(sdo.getBizType());
        Map features = new HashMap<String,String>();
        features.put("simple_name",sdo.getSimpleName());
        features.put("leaders_name",sdo.getLeadersName());
        baselineCreateOrganizationRequest.setFeatures(features);
        baselineCreateOrganizationRequest.setLeaders(sdo.getLeaders());
        baselineCreateOrganizationRequest.setOperatorId(sdo.getOperatorId());
        baselineCreateOrganizationRequest.setOutCode(sdo.getOutCode());
        baselineCreateOrganizationRequest.setPlatformId(sdo.getPlatformId());
        return baselineCreateOrganizationRequest;
    }

    private BaselineUpdateOrganizationRequest updateRequestConverter(OrganizationSDO sdo){
        BaselineUpdateOrganizationRequest baselineUpdateOrganizationRequest = new BaselineUpdateOrganizationRequest();
        baselineUpdateOrganizationRequest.setId(sdo.getId());
        baselineUpdateOrganizationRequest.setName(sdo.getName());
        baselineUpdateOrganizationRequest.setCode(sdo.getCode());
        baselineUpdateOrganizationRequest.setParentId(sdo.getParentId());
        baselineUpdateOrganizationRequest.setType(sdo.getType());
        baselineUpdateOrganizationRequest.setBizId(sdo.getBizId());
        baselineUpdateOrganizationRequest.setBizType(sdo.getBizType());
        Map features = new HashMap<String,String>();
        features.put("simple_name",sdo.getSimpleName());
        features.put("leaders_name",sdo.getLeadersName());
        baselineUpdateOrganizationRequest.setFeatures(features);
        baselineUpdateOrganizationRequest.setOperatorId(sdo.getOperatorId());
        baselineUpdateOrganizationRequest.setOutCode(sdo.getOutCode());
        baselineUpdateOrganizationRequest.setLeaders(sdo.getLeaders());
        baselineUpdateOrganizationRequest.setPlatformId(sdo.getPlatformId());
        return baselineUpdateOrganizationRequest;
    }

    private OrganizationSDO organizationResponseConverter(Map map){
        if(map == null){
            return null;
        }
        Map organizationMap = (Map) map.get("organizationSDO");
        OrganizationSDO organizationSDO = new OrganizationSDO();
        organizationSDO.setId((String) organizationMap.get("id"));
        organizationSDO.setName((String) organizationMap.get("name"));
        organizationSDO.setCode((String) organizationMap.get("code"));
        String type = (String)organizationMap.get("type");
        organizationSDO.setType(StringUtil.isNotEmpty(type)?Integer.valueOf(type):OrganizationTypeEnum.GROUP.getCode());
        organizationSDO.setParentId((String) organizationMap.get("parentId"));
        organizationSDO.setBizId((String) organizationMap.get("bizId"));
        organizationSDO.setBizType((String) organizationMap.get("bizType"));
        //organizationSDO.setWeight(((Double) organizationMap.get("weight")).intValue());
        //organizationSDO.setFunctions((List<String>) organizationMap.get("functions"));
        organizationSDO.setLeaders((String) organizationMap.get("leaders"));
        organizationSDO.setHasChildren((Boolean) organizationMap.get("hasChildren"));
        organizationSDO.setStatus(((Double) organizationMap.get("status")).intValue());
        Map<String, String> features = (Map<String, String>)organizationMap.get("features");
        organizationSDO.setFeatures(features);
        organizationSDO.setSimpleName(StringUtil.isNotEmpty(features.get("simple_name"))?features.get("simple_name"):null);
        organizationSDO.setLeadersName(StringUtil.isNotEmpty(features.get("leaders_name"))?features.get("leaders_name"):null);
        organizationSDO.setOutCode((String) organizationMap.get("outCode"));
        organizationSDO.setPlatformId((String) organizationMap.get("platformId"));
        return organizationSDO;
    }

}
